/**
 * 获取浏览器缓存
 * @param {string} type sessionStorage/localStorage
 * @param {string} key 缓存key
 * @returns {Object}
 */
function _getStorage(type, key) {
  let str = window[type].getItem(key)
  try {
    return JSON.parse(str)
  } catch (e) {
    return str
  }
}
/**
 * 设置浏览器缓存
 * @param {string} type sessionStorage/localStorage
 * @param {string} key 缓存key
 * @param {any} value 值
 */
function _setStorage(type, key, value) {
  let val = ''
  if (value instanceof Date) {
    val = value
  } else if (typeof value === 'object') {
    try {
      val = JSON.stringify(value)
    } catch (e) {
      throw new Error('缓存数据格式有误')
    }
  } else {
    val = value
  }
  window[type].setItem(key, val)
}
/**
 * 获取localStorage缓存
 * @param {string} key 缓存key
 */
function getLocalStorage(key) {
  return _getStorage('localStorage', key)
}
/**
 * 获取sessionStorage缓存
 * @param {string} key 缓存key
 */
function getSessionStorage(key) {
  return _getStorage('sessionStorage', key)
}
/**
 * 设置localStorage缓存
 * @param {string} key
 * @param {*} value
 */
function setLocalStorage(key, value) {
  _setStorage('localStorage', key, value)
}

/**
 * 设置sessionStorage缓存
 * @param {string} key
 * @param {*} value
 */
function setSessionStorage(key, value) {
  _setStorage('sessionStorage', key, value)
}

export {
  getLocalStorage,
  getSessionStorage,
  setLocalStorage,
  setSessionStorage
}
